import { useEffect, useRef } from 'react';
import { motion } from 'framer-motion';

const Background = () => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  
  // Create starry background effect using canvas
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    if (!ctx) return;
    
    // Set canvas size to window size
    const resizeCanvas = () => {
      canvas.width = window.innerWidth;
      canvas.height = window.innerHeight;
    };
    
    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();
    
    // Create stars
    const starsCount = 1500;
    const stars = [];
    
    for (let i = 0; i < starsCount; i++) {
      stars.push({
        x: Math.random() * canvas.width,
        y: Math.random() * canvas.height,
        radius: Math.random() * 1.2,
        opacity: Math.random(),
        blinkSpeed: 0.005 + Math.random() * 0.01,
        direction: Math.random() > 0.5 ? 1 : -1
      });
    }
    
    // Animation loop
    const animateStars = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      
      stars.forEach(star => {
        // Update star opacity for twinkling effect
        star.opacity += star.blinkSpeed * star.direction;
        
        // Reverse direction when opacity limits are reached
        if (star.opacity > 1) {
          star.opacity = 1;
          star.direction = -1;
        } else if (star.opacity < 0.2) {
          star.opacity = 0.2;
          star.direction = 1;
        }
        
        // Draw star
        ctx.beginPath();
        ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(255, 255, 255, ${star.opacity})`;
        ctx.fill();
      });
      
      requestAnimationFrame(animateStars);
    };
    
    animateStars();
    
    return () => {
      window.removeEventListener('resize', resizeCanvas);
    };
  }, []);
  
  return (
    <div className="fixed inset-0 z-0">
      {/* Starry background image with overlay */}
      <div className="absolute inset-0 bg-cover bg-center opacity-60" 
        style={{ 
          backgroundImage: 'url(https://lf3-static.bytednsdoc.com/obj/eden-cn/0077eh7fd/pngtree-pure-black-starry-minimalist-dreamy-business-background-picture-image_913719.jpg)' 
        }}
      />
      
      {/* Semi-transparent black overlay */}
      <div className="absolute inset-0 bg-black opacity-70" />
      
      {/* Canvas for star animations */}
      <canvas 
        ref={canvasRef} 
        className="absolute inset-0 w-full h-full"
        style={{ pointerEvents: 'none' }}
      />
    </div>
  );
};

export default Background;